<template>
  <div v-loading="isLoading" class="panel-property">
    <div class="content">
      <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" :component-style="form.componentStyle" />
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form remote-control-button-unique"
        :model="form"
        :rules="rules"
        label-width="30%"
      >
        <BaseOption :form="form" option="tooltipHasLabel" :widget-instance-id="widgetInstanceId" :config="config" />
        <BaseOption :form="form" option="componentStyle" />

        <VsFormItem label="显示名称">
          <el-input v-model="form.name" size="default"> </el-input>
        </VsFormItem>

        <VsFormItem label="二次确认">
          <el-radio-group v-model="form.verifyType" size="default" :fill="activeColorRadio" required>
            <el-radio label="text">文字提示</el-radio>
            <el-radio label="password">密码验证</el-radio>
          </el-radio-group>
        </VsFormItem>

        <VsFormItem label="控制类型">
          <el-radio-group
            v-model="form.type"
            size="default"
            :fill="activeColorRadio"
            required
            @change="controlTypechange"
          >
            <el-radio label="qiting">启停控制</el-radio>
            <el-radio label="kaidu">开度控制</el-radio>
            <el-radio label="speedControl">速度控制</el-radio>
          </el-radio-group>
        </VsFormItem>
        <VsFormItem label="组件描述" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入描述"
            maxlength="200"
            show-word-limit
            required
          >
          </el-input>
        </VsFormItem>
        <VsFormItem v-if="form.type !== 'qiting'" label="输入框和按钮间距">
          <Range v-model:value="form.distance" type="input" :min="0" :max="200" />
        </VsFormItem>
        <div v-if="form.type === 'speedControl'">
          <VsFormItem label="速度档位设置"> </VsFormItem>
          <div class="top-btns">
            <el-button
              class="btn-sure"
              size="default"
              icon="CirclePlus"
              :disabled="addDisable"
              @click.stop="addNewRow(temp, item, 'data')"
            >
              {{ $demoi18n('btn.add') }}
            </el-button>
          </div>
          <el-table
            class="config-panel-table mapping-table"
            :data="form.data"
            :row-style="{ height: '25px' }"
            :header-row-style="{ height: '25px' }"
            max-height="235"
            :header-cell-style="{ lineHeight: '15px' }"
          >
            <el-table-column type="index" :label="$demoi18n('word.serialNumber')" width="60"></el-table-column>
            <el-table-column
              prop="name"
              label="档位"
              width="130"
              :show-overflow-tooltip="true"
              :show-tooltip-when-overflow="true"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].name`"
                  :rules="
                    generateRules({
                      required: true,
                    })
                  "
                >
                  <el-input v-model="scope.row.name" :placeholder="'请输入'" size="default"></el-input>
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="档位值" min-width="100">
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].status`"
                  :rules="
                    generateRules({
                      required: true,
                    })
                  "
                >
                  <el-input v-model="scope.row.status" :placeholder="'请输入'" size="default"></el-input>
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column width="90" :label="$demoi18n('操作')">
              <template #default="scope">
                <el-button
                  icon="SortUp"
                  type="primary"
                  :disabled="scope.$index === 0"
                  link
                  @click.stop="moveUp(scope.$index, scope.row, 'data')"
                ></el-button>
                <el-button
                  icon="SortDown"
                  type="primary"
                  style="margin-left: 1px"
                  :disabled="scope.$index === form.data.length - 1"
                  link
                  @click.stop="moveDown(scope.$index, scope.row, 'data')"
                ></el-button>
                <el-button
                  icon="Delete"
                  type="primary"
                  style="margin-left: 1px"
                  :disabled="delDisable"
                  link
                  @click.stop="deleteCurRow(scope.row, 'data')"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <OptionCollapse>
          <el-collapse-item :title="$demoi18n('echart.setting.component')" name="cssStyle.grid">
            <BaseOption :form="form" option="cssStyle.grid" :df-css-style-attrs="dfCssStyleAttrs.grid" />
          </el-collapse-item>
          <el-collapse-item :title="$demoi18n('word.buttonStyle')" name="cssStyle.allBtn">
            <el-tabs v-model="allBtnActiveTab" class="panel-tab">
              <el-tab-pane :label="$demoi18n('panel.lab.defaultState')" name="default">
                <BaseOption :form="form" option="cssStyle.allBtn" :df-css-style-attrs="dfCssStyleAttrs.allBtn" />
              </el-tab-pane>
              <el-tab-pane :label="$demoi18n('panel.lab.chosenState')" name="actived">
                <VsFormItem :label="$demoi18n('vs-button.synchronizeMasterStyles')">
                  <el-button type="primary" link @click="syncMainStyle(form, 'allBtn_actived')">{{
                    $demoi18n('word.synchronize')
                  }}</el-button>
                </VsFormItem>
                <BaseOption
                  :form="form"
                  option="cssStyle.allBtn_actived"
                  :df-css-style-attrs="dfCssStyleAttrs.allBtn"
                />
              </el-tab-pane>
            </el-tabs>
          </el-collapse-item>
        </OptionCollapse>
      </el-form>
    </div>
    <el-dialog
      v-if="dialogVisable"
      v-model="dialogVisable"
      :title="$demoi18n('vs-button.editButtonStyle')"
      append-to-body
      :class="`${visualThemeClassName} ${xvueNameSpace}`"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="380px"
      @close="cancelBtnConf"
    >
      <el-form
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form remote-control-button-unique"
        :model="curBtn_"
        label-width="30%"
      >
        <el-tabs v-model="selfBtnActiveTab" class="panel-tab">
          <el-tab-pane :label="$demoi18n('panel.lab.defaultState')" name="default">
            <VsFormItem :label="$demoi18n('vs-button.synchronizeMasterStyles')">
              <el-button type="primary" link @click="syncMainStyle(curBtn_, 'btn')">{{
                $demoi18n('word.synchronize')
              }}</el-button>
            </VsFormItem>
            <BaseOption :form="curBtn_" option="cssStyle.btn" :df-css-style-attrs="dfCssStyleAttrs.allBtn" />
          </el-tab-pane>
          <el-tab-pane :label="$demoi18n('panel.lab.chosenState')" name="actived">
            <VsFormItem :label="$demoi18n('vs-button.synchronizeMasterStyles')">
              <el-button type="primary" link @click="syncMainStyle(curBtn_, 'btn_actived')">{{
                $demoi18n('word.synchronize')
              }}</el-button>
            </VsFormItem>
            <BaseOption :form="curBtn_" option="cssStyle.btn_actived" :df-css-style-attrs="dfCssStyleAttrs.allBtn" />
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelBtnConf()">{{ $demoi18n('panel.confirm.cancel') }}</el-button>
          <el-button type="primary" @click="saveBtnConf()">{{ $demoi18n('panel.confirm.ok') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import OptionCollapse from '@/components/common/base-option/option-collapse/option-collapse.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import Range from '@/components/common/range/range.vue';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import panelPropertyBase from '@/mixin/panel-property-base.js';
import { generateRules } from '@/utils/rules';
import BaseOption from '../../common/base-option/base-option.vue';
import config from './config.js';
import cssStyle from './cssStyle-default.js';
import { bus } from './valid.js';

export default {
  name: 'PanelProperty',
  components: {
    BaseOption,
    OptionCollapse,
    PanelLabelOverflowTooltip,
    VsFormItem,
    Range,
  },
  mixins: [panelPropertyBase],
  props: ['config', 'widgetInstanceId', 'widget'],
  data() {
    const { property } = JSON.parse(JSON.stringify(config.config));
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      isLoading: false,
      form: property,
      dfCssStyleAttrs: {},
      dialogVisable: false,
      curBtn: {},
      curBtn_: {},
      allBtnActiveTab: 'default',
      selfBtnActiveTab: 'default',
      ratio: '',
      rules: {
        desc: generateRules({ required: true, label: '描述', max: 200 }),
      },
      temp: {},
      item: {
        status: '',
        name: '',
      },
      delDisable: true,
      addDisable: false,
      maxLen: 10,
      minLen: 1,
    };
  },
  computed: {

    // 将无图标的count配置项转化为this.form.data.length值，与带图标的组件逻辑统一
    count: {
      get() {
        return this.form.data.length;
      },
      set(v) {
        this.form.data = [];
        const count = v;
        for (let i = 0; i < count; i++) {
          this.temp = JSON.parse(JSON.stringify(this.item));
          this.form.data.push(this.temp);
        }
      },
    },
  },
  watch: {
    'form.data': {
      handler() {
        this.checkLimit();
      },
      deep: true,
    },
  },
  created() {
    this.form = JSON.parse(JSON.stringify(this.config.config.property));
    this.initDfCssStyleAttrs();
    bus.$on(`update-tableData_${this.widgetInstanceId}`, this.onTableDataUpdate);
  },
  methods: {
    moveUp(index, row, group) {
      if (index <= 0) {
        return;
      }
      const temp = this.form[group][index - 1];
      this.form[group].splice(index - 1, 1);
      this.form[group].splice(index, 0, temp);
    },
    moveDown(index, row, group) {
      const temp = this.form[group][index + 1];
      this.form[group].splice(index + 1, 1);
      this.form[group].splice(index, 0, temp);
    },
    addNewRow(temp, item, group) {
      const _temp = JSON.parse(JSON.stringify(item));
      this.form[group].push(_temp);
      if (this.count >= this.minLen) {
        this.delDisable = false;
      }
      if (this.count >= this.maxLen) {
        this.addDisable = true;
      }
    },
    deleteCurRow(item, group) {
      const index = this.form[group].indexOf(item);
      this.form[group].splice(index, 1);
      if (this.count <= this.minLen) {
        this.delDisable = true;
      }
      if (this.count <= this.maxLen) {
        this.addDisable = false;
      }
    },
    checkLimit() {
      const { data } = this.form;
      const nameList = data.map(n => n.name).filter(n => n);
      const aliasList = data.map(n => n.alias).filter(n => n);
      const nameListU = Array.from(new Set(nameList));
      const aliasListU = Array.from(new Set(aliasList));
      if (nameList.length !== nameListU.length || aliasList.length !== aliasListU.length) {
        this.$message.error(this.$demoi18n('message.nameOrAliasRepeated'));
        return false;
      }
      return true;
    },
    controlTypechange() {
      bus.$emit(`changeControlType_${this.widgetInstanceId}`, this.form.type);
    },
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },

    initDfCssStyleAttrs() {
      this.dfCssStyleAttrs = cssStyle;
    },

    addBtn() {
      this.form.buttons.push({ name: '' });
    },

    delBtn(i) {
      this.form.buttons.splice(i, 1);
    },

    setBtnConf(i) {
      this.curBtn = this.form.buttons[i];
      this.curBtn_ = JSON.parse(JSON.stringify(this.curBtn));
      this.curBtn_.componentStyle = this.form.componentStyle;
      this.selfBtnActiveTab = 'default';
      this.dialogVisable = true;
    },

    cancelBtnConf() {
      this.selfBtnActiveTab = 'default';
      this.dialogVisable = false;
    },

    saveBtnConf() {
      Object.assign(this.curBtn, this.curBtn_);
      delete this.curBtn.componentStyle;
      this.dialogVisable = false;
    },

    syncMainStyle(form, key) {
      let style = this.dfCssStyleAttrs.allBtn;
      if (this.form.cssStyle.allBtn) {
        style = this.form.cssStyle.allBtn;
      }
      form.cssStyle[key] = JSON.parse(JSON.stringify(style));
    },
    check() {
      return new Promise(resolve => {
        const { form, ratio } = this;
        if (form.type === 'kaidu' && ratio.length === 0) {
          this.alertMessage('开度百分比不能为空');
          resolve(false);
          return;
        }
        if (form.type === 'speedControl' && ratio.length === 0) {
          this.alertMessage('速度值不能为空');
          resolve(false);
          return;
        }
        this.$refs.form.validate((valid, obj) => {
          resolve(valid);
        });
      });
    },
    alertMessage(message) {
      this.$message({
        message: message,
        type: 'error',
      });
    },
    onTableDataUpdate(tableData) {
      const match = tableData.find(item => item.type === true);
      const { value = '' } = match || {};
      this.ratio = value;
    },
  },
};
</script>
<style lang="less" scoped>
@import '../../common/less/panel-property.less';
</style>
<style lang="less" scoped>
.panel-property {
  .content {
    .prop-form {
      padding: 0 10px;
    }
  }
  .add_btn {
    margin-left: 10px;
  }
  .panel_table {
    .el-button--text {
      padding: 5px 0;
    }
  }
}
</style>
